# -*- coding: utf-8 -*-
from django import forms

from pagedown.widgets import PagedownWidget

from .models import *
import md5
from django.core.exceptions import ValidationError

class MistakeForm(forms.ModelForm):
    error_css_class = "error"
    class Meta:
        model = Question
        fields = [
            "expresstion",
            "process",
            "solution",
            "level",
            "topic"
        ]
        error_messages={
            "level":{
                'min_value':"不能小于1"
            }
        }
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user','')
        print kwargs
        if 'question' in kwargs:
            self.id=kwargs['question'].id
        super(MistakeForm, self).__init__(*args, **kwargs)
    def clean_expresstion(self):
        expresstion=md5.new(self.cleaned_data['expresstion'].encode('utf-8')).hexdigest()
        # if Question.objects.filter(md5string=expresstion).exists():
        #     raise ValidationError('*题目已经存在')
        qs=Question.objects.filter(md5string=expresstion)
        if self.id:
            qs.exclude(pk.self.id)
        if qs.count()>0:
            raise ValidationError('*题目已经存在')
        return self.cleaned_data['expresstion']


